package com.jihox.abookpro;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jihox.abookpro.R;
import com.jihox.abookpro.dao.OrderDAO;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.helper.UserHelper;
import com.jihox.abookpro.uploader.OnProgressListener;
import com.jihox.abookpro.uploader.UploadService;
import com.jihox.abookpro.util.ConfigProperties;
import com.jihox.abookpro.util.MyProgressBar;
import com.jihox.abookpro.util.NetStatus;
import com.jihox.abookpro.view.JHProgressDialog;

public class PaySuccessActivity extends BaseActivity {
	private UploadService uploadService;
	private MyProgressBar mProgressBar;
	private Order orderInfo;
	private Context context;
//	private TextView tvOrderId;
	private JHProgressDialog pd;
	private LinearLayout waitingOrdersLayout;
	private TextView waitingOrdersText;
	private String completedOrders ="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pay_success);
		context = this.getApplicationContext();
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		orderInfo = (Order) bundle.getSerializable("orderInfo");	
//		tvOrderId = (TextView) findViewById(R.id.tvOrderId);		
		mProgressBar = (MyProgressBar) findViewById(R.id.uploadProgressBar);
		waitingOrdersLayout =  (LinearLayout) findViewById(R.id.waiting_orders_num_layout);
		waitingOrdersText = (TextView) findViewById(R.id.waiting_orders_num);
		
		//uploadFile();
//		Button selectOrderButton = (Button) findViewById(R.id.btnSelectOrder);
//		Button returnHomeButton = (Button) findViewById(R.id.btnReturnHome);
		Button returnButton = (Button) findViewById(R.id.btnReturn);
		returnButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent();
				if (orderInfo.getBookProject()!=null && orderInfo.getBookProject().getBook().getProduct().getCategory()==2){
					intent.putExtra("AblumHome", false);
				}
				intent.setClass(PaySuccessActivity.this, HomeChangeActivity.class);
				PaySuccessActivity.this.startActivity(intent);
				finish();
			}
		});

//		returnHomeButton.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View view) {
//
//				Intent intent = new Intent();
//				if (orderInfo.getBookProject()!=null && orderInfo.getBookProject().getBook().getProduct().getCategory()==2){
//					intent.putExtra("AblumHome", false);
//				}
//				intent.setClass(PaySuccessActivity.this, HomeChangeActivity.class);
//				PaySuccessActivity.this.startActivity(intent);
//				finish();
//			}
//
//		});

//		selectOrderButton.setOnClickListener(new OnClickListener() {
//			@Override
//			public void onClick(View arg0) {
//
//				Intent intent = new Intent();
//				if (orderInfo.getBookProject()!=null && orderInfo.getBookProject().getBook().getProduct().getCategory()==2){
//					intent.putExtra("AblumHome", false);
//				}
//				intent.setClass(PaySuccessActivity.this,
//						HomeChangeActivity.class);
//				intent.putExtra("FragmentIndex", 1);
//				PaySuccessActivity.this.startActivity(intent);
//				finish();
//			}
//
//		});
	}
	
	@Override
	public void onResume(){
		super.onResume();
		Intent sIntent = new Intent();
		ComponentName cn = new ComponentName(this, "com.jihox.abookpro.uploader.UploadService");  
		sIntent.setComponent(cn); 
		int dialogWidth = (int)(getWindowManager().getDefaultDisplay().getWidth() * 0.8);
		sIntent.putExtra("DialogWidth", dialogWidth);
		startService(sIntent);
		bindService(sIntent, conn, Context.BIND_AUTO_CREATE);
	}
	
	@Override
    protected void onStart() {
        super.onStart();
        SharedPreferences sp = getSharedPreferences("PAYSUCCESSACTIVITYINFO", MODE_PRIVATE);
        Editor ed = sp.edit();
        ed.putBoolean("active", true);
        ed.commit();
    }
	

	@Override
    protected void onStop() {
        super.onStop();
        SharedPreferences sp = getSharedPreferences("PAYSUCCESSACTIVITYINFO", MODE_PRIVATE);
        Editor ed = sp.edit();
        ed.putBoolean("active", false);
        ed.commit();
        Log.d("pay success", "pay success on stop");
    }

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();
			if (orderInfo.getBookProject()!= null && orderInfo.getBookProject().getBook().getProduct().getCategory()==2){
				intent.putExtra("AblumHome", false);
			}else{
				intent.putExtra("AblumHome", true);
			}
			intent.setClass(PaySuccessActivity.this, HomeChangeActivity.class);
			PaySuccessActivity.this.startActivity(intent);
			finish();
		}
		return false;
	}

	private void uploadFile() {
		
		if (NetStatus.isWifi(context)) {
			if(orderInfo.getOldWorksn() == null)
				uploadService.addUploadTask(orderInfo);
			else {
				pd = JHProgressDialog.show(this, null,
						getResources().getString(R.string.X_Submiting_Order));
				againOrderThread.start();
			}
		} else {
			dialog();
		}
	}

	private Thread againOrderThread = new Thread(){
		
		private final int REQUEST_TIMEOUT = 10*1000;
		private final int SO_TIMEOUT = 10*1000;
		private Handler handler = new Handler(Looper.getMainLooper()){
			@Override
			public void handleMessage(Message msg){
				pd.dismiss();
				switch (msg.what) {
				case 1:
					//返回成功，不用再次上传
					mProgressBar.setProgress(100);
					
					//更新订单状态
					orderInfo.setOrderStatus(Order.ORDER_STATUS_UPLOADED);
					OrderDAO dao = new OrderDAO(PaySuccessActivity.this);
					dao.updateOrderStatus(orderInfo);
					Bundle bundle = new Bundle();
					Intent i = new Intent(PaySuccessActivity.this,
							SubmitSuccessActivity.class);
					
					bundle.putString("OrderCode", orderInfo.getOrderId());
					bundle.putString("OrderDeliveryCycle",
							String.valueOf(orderInfo.getOrderDeliveryCycle()));
					i.putExtras(bundle);
					startActivity(i);
					finish();
					break;
					
				default:
					//返回错误，再次上传
					uploadService.addUploadTask(orderInfo);
					break;
				}
			}
		};
		
		@Override
		public void run(){
			String url = ConfigProperties.getAgainOrder();
			HttpPost httpPost = new HttpPost(url);
			UserHelper helper = new UserHelper();
			httpPost.setHeader("username", helper.getUserName());
			httpPost.setHeader("password", helper.getPassword());
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("workid", orderInfo.getOldWorksn()));
			params.add(new BasicNameValuePair("orderid",orderInfo.getOrderId()));
			Log.d("PaySuccessActivity","workid = " + orderInfo.getOldWorksn() + " orderId = " + orderInfo.getOrderId());
			try {
				httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
				
				BasicHttpParams httpParams = new BasicHttpParams();  
			    HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);  
			    HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);  
				HttpClient httpclient = new DefaultHttpClient(httpParams);
				HttpResponse httpResponse = httpclient.execute(httpPost);
				String result = EntityUtils.toString(httpResponse.getEntity());
				Log.d("PaySuccessActivity",result);
				JSONObject resultJSON = new JSONObject(result);
				if(resultJSON.getBoolean("success"))
				{
					handler.sendEmptyMessage(1);
				}else {
					handler.sendEmptyMessage(2);
				}
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
				handler.sendEmptyMessage(2);
			} catch (ClientProtocolException e) {
				e.printStackTrace();
				handler.sendEmptyMessage(2);
			} catch (IOException e){
				e.printStackTrace();
				handler.sendEmptyMessage(2);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				handler.sendEmptyMessage(2);
			}
		}
	};
	
	private void dialog() {

		final Dialog dialog = new Dialog(PaySuccessActivity.this, R.style.JHDialog);
		//设置它的ContentView
		dialog.setContentView(R.layout.dialog_general);
		Button buttonOK = (Button) dialog.findViewById(R.id.dialog_button_ok);
		Button buttonCancel = (Button) dialog.findViewById(R.id.dialog_button_cancel);

		TextView dialogTitle = (TextView) dialog.findViewById(R.id.dialog_title);
		TextView dialogMessage = (TextView) dialog.findViewById(R.id.dialog_message);

		buttonOK.setBackgroundResource(R.drawable.green_style);
		buttonCancel.setBackgroundResource(R.drawable.grey_style);
		buttonOK.setText(R.string.T_Continue_Text);
		buttonCancel.setText(R.string.T_Later_Upload);
		dialogTitle.setText(getResources().getString(R.string.T_DataFlow_Remind));
		File file = new File(orderInfo.getZipFilePath());
		DecimalFormat df = new DecimalFormat();
		df.setMaximumFractionDigits(2);
		dialogMessage.setText(getResources().getString(R.string.T_Net_Use_Remind)
				+ df.format((double) ((file.length() * (float)(100-orderInfo.getUploadProgress())/100) / 1024 / 1024)) + getResources().getString(R.string.T_Net_Use_Continue));
		dialog.setCanceledOnTouchOutside(false);
		
		buttonOK.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				// 绑定Service
				uploadService.setWifiUpload(false);
				uploadService.addUploadTask(orderInfo);
			}
		});
		buttonCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
				Intent intent = new Intent(PaySuccessActivity.this,
						SubmitFailActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("orderInfo", orderInfo);
				intent.putExtras(bundle);
				PaySuccessActivity.this.startActivity(intent);
				finish();
			}
		});
		
		dialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					dialog.dismiss();
					Intent intent = new Intent(PaySuccessActivity.this,
							SubmitFailActivity.class);
					Bundle bundle = new Bundle();
					bundle.putSerializable("orderInfo", orderInfo);
					intent.putExtras(bundle);
					PaySuccessActivity.this.startActivity(intent);
					finish();
					return true;
				}
				return false;
			} 
        });

		dialog.show();
	}
	
	ServiceConnection conn = new ServiceConnection() {  
        @Override  
        public void onServiceDisconnected(ComponentName name) {  
              
        }  
          
        @Override  
        public void onServiceConnected(ComponentName name, IBinder service) {  
            //返回一个MsgService对象  
        	uploadService = ((UploadService.UploadBinder)service).getService();  
              
            //注册回调接口来接收下载进度的变化  
        	uploadService.setOnProgressListener(new OnProgressListener() {  

				@Override
				public void onProgress(String orderId, int status,
						int progress, List<String> waitingOrders) {
					Log.d("receive progress", "orderId:" + orderId);
					Log.d("receive progress", "status:" + status);
					Log.d("receive progress", "progress:" + progress);
//					tvOrderId.setText(orderId);
					mProgressBar.setProgress(progress);
					
					if (waitingOrders!=null && waitingOrders.size()>0){
						waitingOrdersLayout.setVisibility(View.VISIBLE);
						waitingOrdersText.setText(waitingOrders.size() + getResources().getString(R.string.X_Waiting_Orders_Text));
					}else{
						waitingOrdersLayout.setVisibility(View.GONE);
					}
					Intent i = null;
					Bundle bundle =null;
					if (status == Order.ORDER_STATUS_UPLOADING){
						return;
					}else if (status == Order.ORDER_STATUS_UPLOADED){
						i = new Intent(PaySuccessActivity.this,
								SubmitSuccessActivity.class);
						completedOrders = completedOrders + "," + orderId;
						if (waitingOrders == null || waitingOrders.size()==0){
							bundle = new Bundle();
							bundle.putString("OrderCode", completedOrders.substring(1));
							bundle.putString("OrderDeliveryCycle",
									String.valueOf(orderInfo.getOrderDeliveryCycle()));
						}else{
							return;
						}
					}else{
						i = new Intent(PaySuccessActivity.this,
								SubmitFailActivity.class);
						if (orderInfo.getBookProject()!=null && orderInfo.getBookProject().getBook().getProduct().getCategory() == 2){
							i.putExtra("AblumHome", false);
						}
						bundle = new Bundle();
						bundle.putSerializable("orderInfo", orderInfo);
					}
					i.putExtras(bundle);
					startActivity(i);
					finish();	
				}  
            }); 
        	//上传文件
        	uploadFile();
        }  
    }; 

	@Override
	protected void onDestroy() {
		Log.d("pay success", "pay success on onDestroy");
//		if (uploadService!=null){
//			uploadService.setOnProgressListener(null);
//		}
		this.unbindService(conn);
		super.onDestroy();
	}
}
